package cn.michael.dev.sort;

/**
 * Created by hufenggang on 2021/8/30.
 *
 * 冒泡排序算法
 */
public class BubbleSort {

    public void bubbleSort(int[] arr, int n) {
        if (n <= 1) {
            return;
        }

        for (int i = 0; i < n; i++) {
            // 提前退出冒泡排序的标志位
            boolean flag = false;

            for (int j = 0; j < n - 1; j++) {
                if (arr[j] > arr[j+1]) {
                    int tmp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = tmp;
                    flag = true;
                }
            }

            if (!flag) {
                break;
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {3, 5, 4, 1, 2, 6};
        BubbleSort bubbleSort = new BubbleSort();
        bubbleSort.bubbleSort(arr, arr.length);

        for(int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}
